package com.tools.scanner.ui.pdf

import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.FileProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.tools.scanner.BaseActivity
import com.tools.scanner.R
import com.tools.scanner.database.PdfInfo
import com.tools.scanner.database.ScannerDatabase
import com.tools.scanner.databinding.ActivityPreviewPdfBinding
import com.tools.scanner.databinding.RecyclerPdfPreviewBinding
import com.tools.scanner.ui.dialog.InputPdfNameDialog
import com.tools.scanner.utils.AppUtil
import com.tools.scanner.utils.DataReportUtil
import com.tools.scanner.utils.ImageUtil
import com.tools.scanner.utils.ToastUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONArray
import java.io.File

class PreviewPdfActivity : BaseActivity() {

    companion object {
        private const val PDF_INFO_DATA = "pdfInfo"
        private const val IS_SAVE_FINISH = "isSaveFinish"

        fun actionStart(context: Context, pdfInfo: PdfInfo, isSaveFinish: Boolean = false) {
            val intent = Intent(context, PreviewPdfActivity::class.java)
            intent.putExtra(PDF_INFO_DATA, pdfInfo)
            intent.putExtra(IS_SAVE_FINISH, isSaveFinish)
            context.startActivity(intent)
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putSerializable(PDF_INFO_DATA, mPdfInfo)
    }

    private lateinit var mBinding: ActivityPreviewPdfBinding
    private val mAdapter = PdfPreviewAdapter()
    private val imageList = mutableListOf<Uri>()
    private var isSaveFinish = false

    private var mPdfInfo: PdfInfo? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityPreviewPdfBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        mPdfInfo = if (savedInstanceState != null) {
            savedInstanceState.getSerializable(PDF_INFO_DATA) as? PdfInfo
        } else {
            isSaveFinish = intent.getBooleanExtra(IS_SAVE_FINISH, false)
            intent.getSerializableExtra(PDF_INFO_DATA) as? PdfInfo
        }

        val pdfInfo = mPdfInfo
        if (pdfInfo == null) {
            finish()
            return
        }

        if (isSaveFinish) {
            AppUtil.rateUs(this)
        }

        mBinding.tvName.text = pdfInfo.name

        try {
            val jsonArray = JSONArray(pdfInfo.photoPath)
            val length = jsonArray.length()
            for (index in 0 until length) {
                imageList.add(Uri.parse(jsonArray.getString(index)))
            }
        } catch (e: Exception) {
            e.printStackTrace()
            finish()
            return
        }

        setupRecyclerView()

        mBinding.ivBack.setOnClickListener {
            finish()
        }

        mBinding.tvName.setOnClickListener {
            showNameDialog()
        }

        mBinding.ivEdit.setOnClickListener {
            mBinding.tvName.performClick()
        }

        mBinding.llSharePdf.setOnClickListener {
            DataReportUtil.reportClickPdfShare()

            val pdfFile = File(pdfInfo.pdfPath)

            val pdfUri = FileProvider.getUriForFile(
                this,
                "$packageName.fileprovider", pdfFile
            )

            val shareIntent = Intent().apply {
                action = Intent.ACTION_SEND
                putExtra(Intent.EXTRA_STREAM, pdfUri)
                type = "application/pdf"
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            }

            try {
                startActivity(Intent.createChooser(shareIntent, ""))
            } catch (e: Exception) {
                e.printStackTrace()
                DataReportUtil.reportPdfShareFil(e.toString())
            }
        }

        mBinding.llSaveImg.setOnClickListener {
            showLoadingDialog()
            DataReportUtil.reportClickPdfSave()
            lifecycleScope.launch(Dispatchers.IO) {
                val imageUri: List<Uri> = mAdapter.getAllData()
                ImageUtil.saveToGallery(this@PreviewPdfActivity, imageUri)

                withContext(Dispatchers.Main) {
                    hideLoadingDialog()
                    ToastUtil.showToast(R.string.save_success)
                }
            }
        }

        mBinding.llFinish.setOnClickListener {
            finish()
        }
    }

    private fun setupRecyclerView() {
        val topMargin = resources.getDimension(R.dimen.dp_10).toInt()
        val rightMargin = resources.getDimension(R.dimen.dp_10).toInt()

        mBinding.recyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) {
                super.getItemOffsets(outRect, itemPosition, parent)

                if (itemPosition == 0 || itemPosition % 2 == 0) {
                    outRect.right = rightMargin
                }

                if (itemPosition != 0 && itemPosition != 1) {
                    outRect.top = topMargin
                }

            }
        })

        val layoutManager = GridLayoutManager(this, 2)
        mBinding.recyclerView.layoutManager = layoutManager
        mBinding.recyclerView.adapter = mAdapter
        mAdapter.setData(imageList)
    }

    private fun showNameDialog() {
        val imageList = mAdapter.getAllData()
        if (imageList.isEmpty()) {
            return
        }

        val pdfInfo = mPdfInfo ?: return
        InputPdfNameDialog(this, cacheDir, pdfInfo.name) {
            pdfInfo.name = it
            mBinding.tvName.text = it
            saveFileName(pdfInfo)
        }.show()
    }

    private fun saveFileName(pdfInfo: PdfInfo) {
        lifecycleScope.launch(Dispatchers.IO) {
            ScannerDatabase.get().changePdfFileName(pdfInfo)
        }
    }

    override fun getStatusColor(): Int {
        return resources.getColor(R.color.color_1c1c1e)
    }
}

class PdfPreviewAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val imageList = mutableListOf<Uri>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        val binding = RecyclerPdfPreviewBinding.inflate(layoutInflater, parent, false)
        return PreviewViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return imageList.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is PreviewViewHolder) {
            holder.refresh(imageList[position], position)
        }
    }

    fun setData(uris: List<Uri>) {
        imageList.clear()
        imageList.addAll(uris)
        notifyDataSetChanged()
    }

    fun getAllData(): List<Uri> {
        return imageList
    }

    class PreviewViewHolder(private val mBinding: RecyclerPdfPreviewBinding) :
        RecyclerView.ViewHolder(mBinding.root) {
        fun refresh(uri: Uri, position: Int) {
            mBinding.imageView.let {
                Glide.with(it).load(uri).into(it)
            }

            val num = if (position < 10) {
                "0${position + 1}"
            } else {
                "${position + 1}."
            }

            mBinding.tvNum.text = num
        }
    }
}